package com.bluemobi.system.ctl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.bluemobi.framework.base.BaseCtl;
import com.bluemobi.framework.base.Page;
import com.bluemobi.framework.common.Servlets;
import com.bluemobi.framework.constant.SystemConstant;
import com.bluemobi.system.model.SysUser;
import com.bluemobi.system.service.SysRoleService;
import com.bluemobi.system.service.SysUserService;

/**
 * 系统用户管理Ctl
 *
 * @author wangchen
 */
@Controller
@RequestMapping("/system/user")
public class SysUserCtl extends BaseCtl {

	@Resource
	private SysRoleService sysRoleService;

	@Resource
	private SysUserService sysUserService;

	/**
	 * 获取所有系统用户跳转到系统用户管理首页
	 *
	 * @param pageNO
	 *            页数
	 * @param pageSize
	 *            每页数量
	 * @param sort
	 *            排序字符串
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("system_user")
	@RequestMapping(value = "")
	public String toIndex(@RequestParam(value = "pageNO", defaultValue = "0") Integer pageNO,
			@RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "createDate DESC") String sort, ModelMap model,
			HttpServletRequest request) {
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			model.put("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
			model.put("roleList", sysRoleService.getAllRole(getSysUser(), true));
			searchParams.put("orgIds", getSysUser().getDbPmss());
			model.put("page",
					sysUserService.getUserListByOrgIds(new Page(pageNO, pageSize, 0, sort, null), searchParams));
			// 将查询的map转换成对象
			SysUser user = new SysUser();
			BeanUtils.populate(user, searchParams);
			model.put("user", user);
		} catch (Exception e) {
			Map<String, Object> map = new HashMap<>();
			map.put("status", SystemConstant.RETURN_STATUS_FAIL);
			map.put("msg", SystemConstant.RETURN_MSG_ERROR);
			model.put("msg", JSON.toJSONString(map));
		}
		return "/system/user/index";
	}

	/**
	 * 查看用户详情
	 *
	 * @param suId
	 *            用户ID
	 * @param backParam
	 *            回调参数
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_details")
	@RequestMapping(value = "details/{suId}")
	public String details(@PathVariable String suId, String backParam, ModelMap model) {
		try {
			model.put("user", sysUserService.getById(suId));
			model.put("paramMap", paramUnits(backParam));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return "/system/user/details";
	}

	/**
	 * 跳转到添加页面
	 *
	 * @param backParam
	 *            回掉参数
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_save")
	@RequestMapping(value = "save")
	public String toAdd(String backParam, ModelMap model) {
		model.put("backParam", backParam);
		model.put("paramMap", paramUnits(backParam));
		return "system/user/save";
	}

	/**
	 * 添加用户
	 *
	 * @param sysUser
	 *            用户信息
	 * @param backParam
	 *            回调参数
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_save")
	@RequestMapping(value = "dosave")
	public String doAdd(SysUser sysUser, String backParam, ModelMap model, RedirectAttributes redirectAttributes) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("status", SystemConstant.RETURN_STATUS_FAIL);
		resultMap.put("msg", SystemConstant.RETURN_MSG_ERROR);
		try {
			if (sysUserService.saveSysUser(sysUser)) {
				model.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
				model.put("msg", "添加成功");
				model.put("action", "system/user");// 跳转的form action
				return "/common/redirect";
			}
		} catch (Exception e) {// 添加失败重新跳转到添加页面
			if (e.getMessage().length() < 20) {
				resultMap.put("msg", e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("msg", JSON.toJSONString(resultMap));
		redirectAttributes.addFlashAttribute("user", sysUser);
		redirectAttributes.addFlashAttribute("paramMap", paramUnits(backParam));
		return "redirect:system/user/save";
	}

	/**
	 * 跳转到修改页面
	 *
	 * @param suId
	 *            用户ID
	 * @param backParam
	 *            回掉参数
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_modify")
	@RequestMapping(value = "modify/{suId}")
	public String modify(@PathVariable String suId, String backParam, ModelMap model) {
		model.put("backParam", backParam);
		model.put("paramMap", paramUnits(backParam));
		try {
			model.put("user", sysUserService.getById(suId));
		} catch (Exception e) {
			Map<String, Object> map = new HashMap<>();
			map.put("status", SystemConstant.RETURN_STATUS_FAIL);
			map.put("msg", SystemConstant.RETURN_MSG_ERROR);
			model.put("msg", JSON.toJSONString(map));
			logger.error("跳转到修改页面异常：" + e.getMessage());
		}
		return "system/user/modify";
	}

	/**
	 * 修改用户
	 *
	 * @param sysUser
	 *            用户信息
	 * @param backParam
	 *            回掉参数
	 * @param model
	 *            model
	 * @param redirectAttributes
	 *            临时存储
	 * @return String
	 */
	@RequiresPermissions("user_modify")
	@RequestMapping(value = "domodify")
	public String domodify(SysUser sysUser, String backParam, ModelMap model, RedirectAttributes redirectAttributes) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("status", SystemConstant.RETURN_STATUS_FAIL);
		resultMap.put("msg", SystemConstant.RETURN_MSG_ERROR);
		model.put("paramMap", paramUnits(backParam));
		try {
			if (sysUserService.updateSysUser(sysUser)) {
				model.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
				model.put("msg", "修改成功");
				model.put("action", "system/user");// 跳转的form action
				return "/common/redirect";
			}
		} catch (Exception e) {// 修改失败重新跳转到添加页面
			if (e.getMessage().length() < 20) {
				resultMap.put("msg", e.getMessage());
			}
		}
		redirectAttributes.addFlashAttribute("msg", JSON.toJSONString(resultMap));
		redirectAttributes.addFlashAttribute("user", sysUser);
		redirectAttributes.addFlashAttribute("backParam", backParam);
		return "redirect:system/user/modify";
	}

	/**
	 * 删除用户
	 *
	 * @param suId
	 *            用户ID
	 * @param backParam
	 *            回调参数
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_del")
	@RequestMapping(value = "delete")
	public String delUser(String suId, String backParam, ModelMap model) {
		model.put("status", SystemConstant.RETURN_STATUS_FAIL);
		model.put("msg", SystemConstant.RETURN_MSG_ERROR);
		try {
			model.put("paramMap", paramUnits(backParam));
			if (sysUserService.delUserBySuId(suId)) {
				model.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
				model.put("msg", "删除成功");
			}
		} catch (Exception e) {
			logger.error("删除用户异常：" + e.getMessage());
			if (e.getMessage().length() < 20) {
				model.put("msg", e.getMessage());
			}
		}
		model.put("action", "system/user");// 跳转的form action
		return "/common/redirect";
	}

	/**
	 * 重置用户密码
	 *
	 * @param suId
	 *            用户ID
	 * @return map
	 */
	@RequiresPermissions("user_modify")
	@RequestMapping(value = "resetpwd/{suId}")
	@ResponseBody
	public Map<String, Object> resetPwd(@PathVariable String suId) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("status", SystemConstant.RETURN_STATUS_FAIL);
		resultMap.put("msg", SystemConstant.RETURN_MSG_ERROR);
		try {
			SysUser user = sysUserService.getById(suId);
			sysUserService.updatePwd(suId, user.getLoginName());
			resultMap.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
			resultMap.put("msg", "密码重置成功");
		} catch (Exception e) {
			logger.error("重置用户密码异常：" + e.getMessage());
			if (e.getMessage().length() < 20) {
				resultMap.put("msg", e.getMessage());
			}
		}
		return resultMap;
	}

	/**
	 * 用户角色授权
	 *
	 * @param suId
	 *            会员主键
	 * @param roleId
	 *            角色ID
	 * @param backParam
	 *            回跳地址串
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_authorize")
	@RequestMapping(value = "authorize")
	public String roleAuthorize(String suId, String roleId, String backParam, ModelMap model) {
		model.put("status", SystemConstant.RETURN_STATUS_FAIL);
		model.put("status", "授权失败");
		try {
			model.put("paramMap", paramUnits(backParam));
			SysUser sysUser = new SysUser();
			sysUser.setSuId(suId);
			sysUser.setRoleId(roleId);
			if (sysUserService.updateSysUser(sysUser)) {
				model.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
				model.put("msg", "授权成功");
			}
		} catch (Exception e) {
			logger.error("取消用户角色授权异常：" + e.getMessage());
		}
		model.put("action", "system/user");// 跳转的form action
		return "/common/redirect";
	}

	/**
	 * 取消用户角色授权
	 *
	 * @param suId
	 *            用户ID
	 * @param backParam
	 *            回跳地址串
	 * @param model
	 *            model
	 * @return String
	 */
	@RequiresPermissions("user_authorize")
	@RequestMapping(value = "delAuthorize")
	public String delAuthorize(String suId, String backParam, ModelMap model) {
		model.put("status", SystemConstant.RETURN_STATUS_FAIL);
		model.put("status", "取消授权失败");
		try {
			model.put("paramMap", paramUnits(backParam));
			SysUser sysUser = new SysUser();
			sysUser.setSuId(suId);
			sysUser.setRoleId("");
			if (sysUserService.updateSysUser(sysUser)) {
				model.put("status", SystemConstant.RETURN_STATUS_SUCCESS);
				model.put("msg", "取消授权成功");
			}
		} catch (Exception e) {
			logger.error("取消用户角色授权异常：" + e.getMessage());
		}
		model.put("action", "system/user");// 跳转的form action
		return "/common/redirect";
	}
}
